package gui.clock;

import gui.EarthPanel;

import java.awt.event.ActionEvent;
import java.util.Iterator;
import java.util.List;

import javax.swing.JOptionPane;

import common.IGrid;

public class FakeClock extends AbstractClock {
  private static final long serialVersionUID = -8780400385217446771L;
  private EarthPanel pnlEarth;
  private ClockDisplay clockDisplay;
  private long elapsedTime = 0;
  private long duration;
  private int intervalCounter = 0;
  private int interval = 0;
  private Iterator cachedGridIterator;
  
  public FakeClock(EarthPanel pnlEarth, ClockDisplay clockDisplay) {
    super();
    this.pnlEarth = pnlEarth;
    this.clockDisplay = clockDisplay;
  }
  
  public void pause() {
    dateTimeClock.stop();
  }

  public void reset() {
    dateTimeClock.stop();
    clockDisplay.reset();
    pnlEarth.reset();
    settings.reset();
    elapsedTime = 0;
    intervalCounter = 0;
  }

  public void start() {
    setSimTimeStep(settings.getTimeStep());
    duration = settings.getEndDateTime() - settings.getStartDateTime();
    cachedGridIterator = settings.getCachedGrids().iterator();
    dateTimeClock.start();
  }

  public void actionPerformed(ActionEvent e) {
    elapsedTime += simTimeStep;
    if (elapsedTime >= duration) {
      pause();
      if(elapsedTime > duration) {
        elapsedTime -= simTimeStep;
        JOptionPane.showMessageDialog(
          clockDisplay, 
          "Lower your time step to complete the simulation.",
          "Incomplete Simulation...",
          JOptionPane.INFORMATION_MESSAGE);
        settings.resetRunButton();
      }
      else {
        //simulation complete after this step
        step();
        settings.finalStep();
      }
    }
    else {      
      step();      
    }
  }
  
  private void step() {
    Object obj = cachedGridIterator.next();
    IGrid grid = (IGrid) obj;
    if(settings.isAnimation()) {
      pnlEarth.updateGrid(grid);
      pnlEarth.moveSunPosition(sunDegStep);
      clockDisplay.increment(simTimeStep);
    }
  }

}
